

<template>
    <view class="groupMembers">
        <!-- <image
            class="psa"
            style="width:750rpx;height:834rpx;top:0;left:0;right:0;z-index:1;"
            src="../../static/bg1.jpg"
            mode=""
        ></image> -->
        <view
            style="
                background: #fff;
                width: 750rpx;
                position: fixed;
                z-index: 100;
            "
            :style="{ height: systemInfo.statusBarHeight + 'px' }"
        ></view>
        <view
            class="slim_header d-flex a-center j-center"
            style="border-bottom: none"
            :style="{ top: systemInfo.statusBarHeight + 'px' }"
        >
            <view class="left_box" @tap="goBack">
                <image src="/static/center/back.png" class="back"></image>
            </view>
            <view class="title d-flex a-center j-between">邀请入群</view>
            <view class="right_box">
                <!-- <image src="/static/center/dian.png" class="dian"></image> -->
            </view>
        </view>

        <view
            class="search_box d-flex a-center j-center"
            :style="{ top: `calc(  100rpx + ${systemInfo.statusBarHeight}px)` }"
        >
            <view class="search d-flex a-center">
                <i
                    class="tmicon tmicon-search"
                    style="color: #ccc; font-size: 30rpx"
                ></i>
                <input
                    type="text"
                    class="inp"
                    @input="searchAddressBook"
                    v-model="searchText"
                    placeholder="好友昵称"
                    placeholder-style="color:#ccc;font-size:25rpx;"
                />
            </view>
        </view>

        <scroll-view
            :scroll-y="true"
            class="content"
            :style="{ top: `calc(  180rpx + ${systemInfo.statusBarHeight}px)` }"
        >
            <view class="box_view">
                <view class="title d-flex d-r a-center j-between"
                    ><text>我的好友</text></view
                >
                <view class="list">
                    <view
                        class="psr row d-flex d-r a-center"
                        v-for="f in friends"
                        :key="f.userID"
                        @tap="toggleCheck(f)"
                    >
                        <view class="head_box psr">
                            <userhead
                                width="95"
                                height="95"
                                :saveKey="f.userID"
                                :isVip="f.profile.level"
                                :src="f.profile.avatar"
                            />
                            <!-- <cacheimg class="head" :src="f.profile.avatar" :saveKey="f.userID"></cacheimg>
                                <image
                                    v-if="f.profile.level===2"
                                    class="vip_icon w-center"
                                    src="/static/svip.png"
                                ></image>
                                <image
                                    v-if="f.profile.level===1"
                                    class="vip_icon w-center"
                                    src="/static/vip.png"
                                ></image> -->
                        </view>
                        <view class="name"
                            ><rich-text :nodes="f.nodes"></rich-text
                        ></view>
                        <view class="line"></view>

                        <view
                            class="joined h-center"
                            v-if="isJoined(f)"
                            style="right: 30rpx"
                            >已入群</view
                        >

                        <view v-else class="check_box d-flex a-center j-center h-center">
                            <image v-if="isSelected(f.userID)" class="checkImg" src="@/static/image/diet-menu-check-true.png"></image>
							<image v-else class="checkImg" src="@/static/image/sports-menu-check-false.png"></image>
                        </view>
                    </view>
                </view>
            </view>
        </scroll-view>

        <view class="bottom_box d-flex a-center j-between">
            <scroll-view
                class="selected"
                :scroll-x="true"
                :scroll-y="false"
                :show-scrollbar="false"
                :enable-flex="true"
            >
                <view class="selected_box">
                    <cacheimg
                        class="userhead"
                        style="border: 1px solid #ddd"
                        v-for="item in selected"
                        :saveKey="item.userID"
                        :src="item.profile.avatar"
                        mode="aspectFill"
                    ></cacheimg>
                </view>
            </scroll-view>

            <view class="right_area d-flex d-c">
                <view
                    @tap="handleInvite"
                    class="btn1 d-flex a-center j-center"
                    :class="{ disabled: !selected.length }"
                >
                    邀请{{ selected.length }}人
                </view>
            </view>
        </view>

    </view>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { onReady, onShow, onLoad } from "@dcloudio/uni-app";
import { userData as userDataStore } from "@/store/userData";
import { systemInfo as systemInfoStore } from "@/store/systemInfo";
import { getGroupMember,getCircleDetail,groupAddMember,sendGroupMessageList } from "@/api/api";
import { getFriendList,getGroupProfile } from "@/hooks/imHooks";
import cacheimg from "@/components/cacheimg.vue";
import { imStore as imStore1 } from "@/store/imStore";
import userhead from "@/components/userhead.vue";
import { wait,showLoading,closeLoading,generateSevenDigitRandomNumber } from "@/utils/utils"
import { escapeHtml } from "@/utils/format"
const imStore: any = imStore1();


const searchText = ref("");
const groupMembers:any = ref([]);
const friends:any = ref([]);
const userData: any = userDataStore();
const systemInfo: any = systemInfoStore();
const selected:any = ref([]);


const  goBack = () => {
	uni.navigateBack();
};

const toggleCheck = (f:any) => {
    if (isJoined(f)) {
        return;
    }

    const index = selected.value.findIndex((item:any) => item.userID === f.userID);
    if (index === -1) {
        selected.value.push(f);
    } else {
        selected.value.splice(index, 1);
    }
};

const isSelected = (id:string) => {
    return selected.value.some((item:any) => item.userID === id);
};

const getFriends = async () => {
    const res: any = await getFriendList();
    const { code, data } = res;
    if (code !== 0) {
        return;
    }
    imStore.setFriends(data);
};

const groupDetail:any = ref({});


const getDetail = async (groupId: string) => {
    const res: any = await getCircleDetail({ groupId });
    const { flag, data } = res;
    if (flag !== 1) {
        uni.showToast({
            icon: "none",
            title: "获取群资料失败",
            duration: 1500,
        });
        return;
    }


    groupDetail.value = data;
};

const isJoined = (friend:any) => {
    return groupMembers.value.some((member:any) => member.userId === friend.userID);
};

const initData = () => {
    const clone_all_friends = JSON.parse(JSON.stringify(imStore.friends));
    friends.value = clone_all_friends.map((item:any) => {
        let color = "#333";
        if (item.level) {
            color = "#F19945";
        }

        return {
            ...item,
            nodes: `<div style="color:${color};font-weight:400;">${
				escapeHtml(item.remark || item.profile.nick)
            }</div>`,
        };
    });
	
};

const searchAddressBook = () => {
    if (!searchText.value) {
        initData();
        return;
    }

    friends.value = imStore.friends.filter((item:any) => {
        const str = item.remark || item.profile.nick;
        if (str.toLowerCase().search(searchText.value.toLowerCase()) !== -1) {
            return true;
        } else {
            return false;
        }
    });

    matchTextHighLight();
};

const matchTextHighLight = () => {
    const reg = new RegExp(searchText.value, "gi");
    friends.value = friends.value.map((item) => {
        const obj = {
            ...item,
        };
        // const str = `<div style="color:#555;">${item.profile.nick}</div>`;
        const str = escapeHtml(item.remark || item.profile.nick);
        const nodes = `<div style="color:#555;font-weight:400;">${str.replace(
            reg,
            (s: any) => {
                return `<span style="color:#23e2a6">${s}</span>`;
            }
        )}</div>`;
        obj.nodes = nodes;
        return obj;
    });
};

const reqGroupMember = async (groupId: string) => {
    const res: any = await getGroupMember({ groupId });
    const { flag, data } = res;
    if (flag !== 1) {
        uni.showToast({
            icon: "none",
            title: "获取成员列表失败",
            duration: 1500,
        });
    }
    groupMembers.value = data.list;
};

const sendCustomMessage = (f:any,payload:any) => {

    return new Promise((resolve,reject) => {
        try {
                let message = uni.$TUIKit.createCustomMessage({
                to: f.userID,
                conversationType: 'C2C',
                payload,
            });
            // 3. 发送消息
            uni.$TUIKit.sendMessage(message).then((res:any)=>{
                resolve(res);
            }).catch((err:any)=>{
                resolve(err);
            });
            
        } catch (error) {
            resolve(error);
        }
    })
};
const role = ref("Member");
let loading = false;
const handleInvite = async() => {

    if(loading){
        return
    }

    //showLoading();

    loading = true;

    

    if(!selected.value.length){
        uni.showToast({
            icon: "none",
            title: "请选择好友",
            duration: 1500,
        });

        closeLoading();

        loading = false;

        return
    }
	if(role.value == 'Owner' || role.value == 'Admin'){
		// 使用for...of循环遍历集合  
		const userIDs = []; // 创建一个数组来存储提取出的userID  
		let MsgBody:any = [] //系统通知
		for (const user of selected.value as any) {  
		  // 检查user对象是否包含userID属性  
		  if (user && 'userID' in user) {  
		    // 将userID添加到userIDs数组中  
		    userIDs.push(user.userID);  
			
			//生成系统通知消息
			let ext = {
				applicant:user.userID,
				applicantNick:user.profile.nick,
				inviterId:userData.id,
				inviterName:userData.nickName
			}
			//发送群通知
			let Msg = {
				"MsgType":"TIMCustomElem",
				"MsgContent": {
					"Data": "group_join", 
					"Desc": "群通知",
					"Ext": JSON.stringify(ext) 
				}
			}
			MsgBody.push(Msg)
		  }  
		} 
		let params = {
			groupId: imStore.conversation.groupProfile.groupID,
			ids:userIDs
		}
		let res:any = await groupAddMember(params);
		if(res.success){
			/*
			uni.showToast({
				title:'邀请成功',
				icon:'none',
				duration:1500
			})
			*/
		}else{
			uni.showToast({
				title:res.message,
				icon:'none',
				duration:1500
			})
			return
		}
		let paramsMsg:any = []
		MsgBody.forEach((item:any) => {
			paramsMsg.push({
				"GroupId":imStore.conversation.groupProfile.groupID,
				"Random":generateSevenDigitRandomNumber(),
				"MsgBody":[item]
			})
		})
		//console.log(paramsMsg)
		sendGroupMessageList(paramsMsg).catch(() => {
			uni.showToast({
				title:'通知发送失败',
				icon:'none',
				duration:1500
			})
		})
		/*
		MsgBody.forEach(async (item:any) => {
			let paramsMsg = {
				"GroupId":imStore.conversation.groupProfile.groupID,
				"Random":generateSevenDigitRandomNumber(),
				"MsgBody":[item],
			}
			await sendGroupMessage(paramsMsg).catch(() => {
				uni.showToast({
					title:'通知发送失败',
					icon:'none',
					duration:1500
				})
			})
		})
		*/
		uni.navigateBack({
			success: () => {
				uni.showToast({
					title:'邀请成功',
					icon:'none',
					duration:1500
				})
			}
		})
		/*
		groupAddMember(params).then((res:any) => {
			if(res.success){
				uni.navigateBack({
					success: () => {
						uni.showToast({
							title:'邀请成功',
							icon:'none',
							duration:1500
						})
						MsgBody.forEach((item:any) => {
							let paramsMsg = {
								"GroupId":imStore.conversation.groupProfile.groupID,
								"Random":generateSevenDigitRandomNumber(),
								"MsgBody":[item],
							}
							console.log("**********************************************")
							console.log(paramsMsg)
							sendGroupMessage(paramsMsg).catch(() => {
								uni.showToast({
									title:'通知发送失败',
									icon:'none',
									duration:1500
								})
							})
						})
						
					}
				})
			}else{
				uni.showToast({
					title:res.message,
					icon:'none',
					duration:1500
				})
			}
		})
		*/
	}else{
		const obj = {
		    title: "邀请你加入群~",
		    groupId: imStore.conversation.groupProfile.groupID,
		    name: imStore.conversation.groupProfile.name,
		    avatar:imStore.conversation.groupProfile.avatar,
		    memberCount:imStore.conversation.groupProfile.memberCount,
		    label:groupDetail.value.label,
			inviterId:userData.id,
			inviterName:userData.nickName
		};
		const payload = {
		    data: "2",
		    description: "入群邀请",
		    extension: JSON.stringify(obj),
		};
		
		const arr = JSON.parse(JSON.stringify(selected.value));
		goBack();
		
		uni.showToast({
		    icon: "none",
		    title: "正在发送邀请",
		    duration: 10000,
		});
		
		for(let i=0;i<arr.length;i++){
		    const f = arr[i];
		    await sendCustomMessage(f,payload).catch();
		    await wait(50);
		}
		selected.value = [];
		
		//closeLoading();
		loading = false;
		uni.showToast({
		    icon: "success",
		    title: "入群邀请已发送",
		    duration: 1500,
		});
		
		// setTimeout(()=>{
		//     goBack();
		// },2000)
		
	}
};

onReady(() => {});

onLoad((option: any) => {
    if (option.groupID) {
        Promise.all([reqGroupMember(option.groupID), getFriends(),getDetail(option.groupID)]).then(() => {
            initData();
        });
    }
	getGroupProfile(option.groupID).then((res:any) => {
		if(res.code === 0){
			role.value = res.data.group.selfInfo.role;
		}
	});
});

onShow(() => {});
</script>

<style lang="scss" scoped>
.groupMembers {
    width: 750rpx;
    height: 100vh;
    background: #fff;

    .search_box {
        position: fixed;
        width: 750rpx;
        background: #fff;
        padding-bottom: 20rpx;

        .search {
            width: 690rpx;
            height: 60rpx;
            border-radius: 30rpx;
            background: #f5f5f5;
            padding: 0 30rpx;
            .inp {
                width: 570rpx;
                margin-left: 20rpx;
                font-size: 25rpx;
            }
        }
    }

    .bottom_box {
        position: fixed;
        width: 750rpx;
        height: 120rpx;
        left: 0;
        bottom: constant(safe-area-inset-bottom);
        bottom: env(safe-area-inset-bottom);
        background-color: #fff;
        padding: 0 30rpx;
        .selected {
            height: 80rpx;
            width: 460rpx;
            white-space: nowrap;

            .selected_box {
            }

            .userhead {
                width: 80rpx;
                height: 80rpx;
                border-radius: 10rpx;
                margin-right: 10rpx;
            }
        }

        .right_area {
            .btn1 {
                padding: 0 30rpx;
                height: 80rpx;
                background: linear-gradient(318deg, #64f1c5 0%, #29dba3 100%);
                color: #fff;
                font-size: 32rpx;
                border-radius: 20rpx;
                &.disabled {
                    color: #999;
                    background: #eee;
                }

                &:active{
                    opacity: .7;
                }
            }
        }
    }

    .content {
        position: absolute;
        width: 750rpx;
        left: 0;
        right: 0;
        bottom: calc(constant(safe-area-inset-bottom) + 120rpx);
        bottom: calc(env(safe-area-inset-bottom) + 120rpx);
        background: #f5f5f5;

        .box_view {
            margin-top: 20rpx;
            background: #fff;
            .title {
                height: 60rpx;
                font-size: 28rpx;
                color: #333;
                font-weight: 400;
                padding: 0 30rpx;
            }
            .list {
            }
            .row {
                position: relative;
                padding: 0 30rpx;
                gap: 20rpx;
                height: 110rpx;
                .head_box {
                    width: 95rpx;
                    height: 95rpx;
                    .vip_icon {
                        width: 97rpx;
                        height: 43rpx;
                        bottom: -10rpx;
                    }
                }
                .head {
                    width: 95rpx;
                    height: 95rpx;
                    border-radius: 50%;
                    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.1);
                    border: 3px solid #ffffff;
                }
                .name {
                    margin-left: 10rpx;
                    font-size: 34rpx;
                    color: $slim-text5;
                    &:active {
                    }
                }

                &:active {
                    background: #f5f5f5;
                }
                .line {
                    position: absolute;
                    height: 1px;
                    width: 600rpx;
                    left: 130rpx;
                    background-color: #f5f5f5;
                    bottom: 0;
                }
                .joined {
                    color: #aaa;
                    font-size: 28rpx;
                }
                .check_box {
                    width: 32rpx;
                    height: 32rpx;
                    right: 30rpx;
                    overflow:hidden;
                    .checkImg {
                        width: 32rpx;
                        height: 32rpx;
                    }
                }

                // &::before {
                //     content: "";
                //     position: absolute;
                //     left: 110rpx;
                //     right: 20rpx;
                //     bottom: 0;
                //     height: 1px;
                //     background-color: #f5f5f5;
                // }
            }
        }
    }
}
</style>
